/**
 * Created by liufeng6, 2016-09-27
 * 认证比对app页面
 */
angular.module('rzbd.controller',[])
  .controller('rzbdCtrl',['$scope','$ionicPopup','$ionicLoading','$cordovaCamera','$cordovaBarcodeScanner','$cordovaToast','$timeout','rzbdService','ywkhService','$localstorage',function($scope,$ionicPopup,$ionicLoading,$cordovaCamera,$cordovaBarcodeScanner,$cordovaToast,$timeout,rzbdService,ywkhService,$localstorage){


    $scope.$on('$ionicView.enter', function(event, data) {
      /*console.debug("rzbd entered >>>>>");
      console.log("entered rzbd");
      $scope.isScanQrCodeReady = true;
      $scope.isReadIdCardReady = false;
      $scope.isTakePhotoReady = false;
      $scope.isSubmitReady = false;
      rzbdService.clearIdCardInfo();
      $scope.params = rzbdService.getParams();
      $scope.idCardPhotoSrc0 = "";
      $scope.idCardPhotoSrc1 = "";
      $scope.idCardPhotoSrc2 = "";

      $scope._TESTMODE = false;*/
      $scope.resetPage();
    });

    // 读二代证信息
    $scope.readIdCard = function (){
      //alert("read id card 0");
      var btdevicename = $localstorage.get("mac");
      //alert("read id card 1"+btdevicename);
      //console.debug("before blue tooth");
      if (btdevicename) {
        var btparam = {"mac": btdevicename};
        rzbdService.readIdCardBlueTooth(btparam);
        //console.log("ID CARD INFOMATION: " + JSON.stringify($scope.idCardInfo));
        //document.getElementById("imgIdPic").src="data:image/jpeg;base64,"+rzbdService.bytesToBase64($scope.idCardInfo.avatar);
      } else {
        var alertPopup = $ionicPopup.alert({
          title: '读取失败',
          template: "蓝牙未设置，请先去用户中心设置蓝牙！",
          okText: '确定', // String (默认: 'OK')。OK按钮的文字。
          okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
        });
      }
    };

    // 扫bss二维码
    $scope.scanQrCode = function() {
      //console.debug("scanQrCode >>>>>");
      //alert("开始扫描二维码");
      $cordovaToast.showShortCenter("请扫描BSS页面上的二维码")
        .then(function(success){
          $cordovaBarcodeScanner
            .scan({charset:"utf-8"})
            .then(function(barcodeData) {
              //alert("扫描二维码结束");
              //$timeout(function(){ // barcodeScanner插件存在bug,如果直接获取,有可能导致二次扫码,然后以取消退出,这里设置500毫秒延时,问题解决。
                //alert("QR CODE SCANNED: "+JSON.stringify(barcodeData)); // 应该是"seq_item_id;eparchy_code"这种格式
                if ( barcodeData.cancelled ){
                  $cordovaToast.showShortCenter("二维码扫码取消");
                  $scope.isReadIdCardReady = false;
                }else{
                  var tradeQrCode = barcodeData.text;
                  console.debug("QR CODE SCANNED: "+tradeQrCode);
                  //alert("二维码扫描成功:"+tradeQrCode);
                  //if ( (/\d{16};\d{4}/g).test(tradeQrCode) ){
                  if ( tradeQrCode.split(";").length>=4 ){
                    $scope.rzbdItemId = tradeQrCode.split(";")[0];
                    $scope.rzbdEparchyCode = tradeQrCode.split(";")[1];
                    $scope.rzbdTradeStaffId = tradeQrCode.split(";")[2];
                    $scope.rzbdPsptId = tradeQrCode.split(";")[3];
                    //$scope.rzbdCustName = decodeBase64(tradeQrCode.split(";")[4]);
                    if ( $scope.rzbdTradeStaffId===$localstorage.get("STAFF_ID") ){
                      $scope.isReadIdCardReady = true;
                      $scope.isSubmitReady = true;
                      $ionicPopup.alert({
                        title:"二维码扫描成功",
                        template:"BSS业务受理使用的证件号码为:<b><span style='color:#ff8707'>"+$scope.rzbdPsptId+"</b></span>,请注意核对。",
                        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                        okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
                      });
                    }else{
                      $ionicPopup.alert({
                        title:"失败",
                        template:"BSS业务工号与APP登录工号不一致,不允许进行认证合一比对。",
                        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                        okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
                      });
                      $scope.resetPage();
                    }


                  }else{
                    $ionicPopup.alert({
                      title:"失败",
                      template:"二维码信息有误:"+tradeQrCode+",请重新扫描。",
                      okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                      okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
                    });
                  }
                }
            //  },1000);

            }, function(error) {
              $ionicPopup.alert({
                title:"失败",
                template:"扫描二维码不成功。",
                okText: '确定', // String (默认: 'OK')。OK按钮的文字。
                okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
              });
            });
        });

    };

    // 身份证正面照拍照0-正面;1-反面;2-手持照
    $scope.takeIdCardPhoto = function(idx) {
      console.log(">>>>takeIdCardPhoto:"+idx);
      try{
        var camOptions = {
          quality: 50,
          destinationType: Camera.DestinationType.DATA_URL,
          sourceType: Camera.PictureSourceType.CAMERA,
          allowEdit: false,
          encodingType: Camera.EncodingType.JPEG,
          targetWidth: 600,
          targetHeight: 800,
          popoverOptions: CameraPopoverOptions,
          saveToPhotoAlbum: false,
          correctOrientation:true
        };

        $cordovaCamera.getPicture(camOptions).then(
          function(imageData) {
            //console.log("------------------\n"+imageData);
            //var image = document.getElementById('myImage');
            //document.getElementById("idCardPhoto"+idx).src = "data:image/jpeg;base64," + imageData;
            $scope["idCardPhotoSrc"+idx] = imageData;
            document.getElementById("imgId"+idx).src="data:image/jpeg;base64," + imageData;
            console.log("------------------done:");
          }, function(err) {
            // error
          }
        );
      }catch(e){
        alert(e.message);
      }

    };

    $scope.resetPage = function(){
      $scope.rzbdItemId = "";
      $scope.rzbdTradeStaffId = "";
      $scope.rzbdPsptId = "";
      $scope.rzbdCustName = "";
      $scope.isScanQrCodeReady = true;
      $scope.isReadIdCardReady = true;
      $scope.isTakePhotoReady = true;
      $scope.isSubmitReady = false;
      rzbdService.clearIdCardInfo();
      $scope.params = rzbdService.getParams();
      $scope.idCardPhotoSrc0 = "";
      $scope.idCardPhotoSrc1 = "";
      $scope.idCardPhotoSrc2 = "";
      document.getElementById("imgId0").src = "";
      document.getElementById("imgId1").src = "";
      document.getElementById("imgId2").src = "";
      //document.getElementById("imgIdPic").src = "img/id_avatar.png";
    };

    $scope.submitInfo = function (){
      console.log(">>>>> rzbd submit >>>>>>");
      if ( !($scope.rzbdItemId) || $scope.rzbdItemId=="" || $scope.rzbdItemId==null ){
        $ionicPopup.alert({
          title:"无法提交",
          template:"请扫描业务界面上的二维码。",
          okText: '确定', // String (默认: 'OK')。OK按钮的文字。
          okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
        });
        return false;
      }
      /* if ( document.getElementById("txtIdCardNo").value=="" ){
        var idCardInfo = rzbdService.getParams().idCardInfo;
        if ( idCardInfo==null || idCardInfo=={} ){
          $ionicPopup.alert({
            title:"无法提交",
            template:"请先读取身份证信息。",
            okText: '确定', // String (默认: 'OK')。OK按钮的文字。
            okType: 'item-customer-bg-darkred', // String (默认: 'button-positive')。OK按钮的类型。
          });
          return false;
        }
        $scope.params.idCardInfo = idCardInfo;
      }*/
      /*if ( $scope.idCardPhotoSrc0=="" ||$scope.idCardPhotoSrc1=="" ||$scope.idCardPhotoSrc2=="" ){
        $ionicPopup.alert({
          title:"无法提交",
          template:"需要拍摄身份证正反面,以及本人手持身份证照片,共三张。",
          okText: '确定', // String (默认: 'OK')。OK按钮的文字。
          okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
        });
        return false;
      }*/
      var info = {
        itemId:$scope.rzbdItemId,
        /*eparchyCode:$scope.rzbdEparchyCode,
        //idCardInfo:$scope.idCardInfo,
        idCardNo:$scope.params.idCardInfo.cardNo, //身份证号
        idName:$scope.params.idCardInfo.name, //姓名
        idAuthority:$scope.params.idCardInfo.authority, //发证单位
        idBirth:$scope.params.idCardInfo.birth, //生日
        idAddress:$scope.params.idCardInfo.address, //地址
        idSex:$scope.params.idCardInfo.sex, //性别
        idPeriod:$scope.params.idCardInfo.period.split("-")[1], //有效期
        idAvatar:$scope.params.idCardInfo.avatar64, //照片字节码
        idEthnicity:$scope.params.idCardInfo.ethnicity, //民族*/
        pic0:eval("("+JSON.stringify(imgSrcToStrArr($scope.idCardPhotoSrc0))+")"),
        pic1:eval("("+JSON.stringify(imgSrcToStrArr($scope.idCardPhotoSrc1))+")"),
        pic2:eval("("+JSON.stringify(imgSrcToStrArr($scope.idCardPhotoSrc2))+")")
      };
      //alert("rzbdCtrl submit>>>>>>>>>>>>>>>>>>>>>>\n"+JSON.stringify(info)+"\n>>>>>>>>>>>>>>>>>>>>>>>>");

      //$ionicLoading.show({      });
      rzbdService.submitRzbd(info).then(
        function(data){ //success
          $ionicLoading.hide();
          //console.debug("rzbd submit success: "+JSON.stringify(data));
          if ( data.respCode=="0" ){
            // TODO
            //alert("人证合一比对照片已提交,请等待后台审核。");
            $ionicPopup.alert({
              title:"提交完成",
              template:"人证合一比对照片已提交,请等待后台审核。",
              okText: '确定', // String (默认: 'OK')。OK按钮的文字。
              okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
            });
            $scope.isSubmitReady = true;
          } else {
            $ionicPopup.alert({
              title:"提交失败",
              template:"人证合一比对照片提交失败:"+data.respDesc,
              okText: '确定', // String (默认: 'OK')。OK按钮的文字。
              okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
            });
          }

        },
        function(error){ //fail
          $ionicLoading.hide();
          console.error("rzbd submit fail: "+error);
          $ionicPopup.alert({
            title:"提交失败",
            template:"人证合一比对照片提交异常。",
            okText: '确定', // String (默认: 'OK')。OK按钮的文字。
            okType: 'item-customer-bg-darkred' // String (默认: 'button-positive')。OK按钮的类型。
          });
        }
      );
    };
    $scope.alertAvatar = function(){
      alert($scope.idCardInfo.avatar);
    };
    function imgSrcToStrArr(src, segLength) {
      if (!segLength){
        segLength=5120;
      }
      var arr = [];
      //alert(Math.ceil(src.length / segLength)+" segments with segments length: "+segLength);
      if (src.length > segLength) {
        for (var i = 0; i < src.length / segLength; i++) {
          arr.push(src.substring(i * segLength, (i+1) * segLength));
        }

      } else {
        arr.push(src);
      }

      return arr;
    }

  }]);
